//
//  Tool_dynamic.swift
//  StoreManage
//
//  Created by MC on 2017/12/22.
//  Copyright © 2017年 MC. All rights reserved.
//

import Foundation




public func MCUserinfo_getUserId() -> Int {
    return Int(UserDefaults.LoginInfo.get(forKey: .userId)!)!
}


public func MCUserinfo_getNickName() -> String {
    return UserDefaults.LoginInfo.get(forKey: .nickName)!
}

public func MCUserinfo_getUserLogo() -> String {
    return UserDefaults.LoginInfo.get(forKey: .picture)!
}

public func MCUserinfo_getUserName() -> String {
    return UserDefaults.LoginInfo.get(forKey: .userName)!
}

public func MCUserinfo_getStoreId() -> Int {
    return Int(UserDefaults.LoginInfo.get(forKey: .storeId)!)!
}

public func MCUserinfo_getToken() -> String {
    return UserDefaults.LoginInfo.get(forKey: .token)!
}


public func MCUserinfo_getStoreName() -> String {
    return UserDefaults.LoginInfo.get(forKey: .storeName)!
}

public func MCUserinfo_getStoreLogo() -> String {
    return UserDefaults.LoginInfo.get(forKey: .logoPath)!
}


public func MCUserinfo_getIsBill() -> String {
    return UserDefaults.LoginInfo.get(forKey: .isBill)!
}

public func MCUserinfo_getLevel() -> Int {
    return Int(UserDefaults.LoginInfo.get(forKey: .level)!)!
}

public func MCUserinfo_getLevelName() -> String {
    return UserDefaults.LoginInfo.get(forKey: .levelName)!
}

/** 店铺身份levl转换
 *
 * 分销员 100-149
 * 店员   200-249
 * 店长   300-349
 */

public func MCLevelConversion(level:Int) -> (level:Int,levelName:String) {
    if (level >= 100 && level <= 149) {
        return (MCRole_salesStaff,MCGetConfiguration_salesStaff())
    } else if (level >= 200 && level <= 249) {
        return (MCRole_assistant,MCGetConfiguration_assistantName())
    }  else if (level >= 300 && level <= 349) {
        return (MCRole_manager,MCGetConfiguration_managerName())
    } else {
        return (0,"")
    }
}


// MARK: -
public typealias SuccessClosure = (_ responseObject : [String:Any]) -> Void
public typealias DislikeClosure = (_ responseObject : [String:Any]) -> Void
public typealias FailureClosure = (_ error : Error) -> Void


public func MCNetwork_post(url : String,para : [String : AnyObject],vc : UIViewController?,hudSuperView : UIView? = nil,isHiddenTabbar: Bool, success : @escaping SuccessClosure,dislike : @escaping DislikeClosure,failure : @escaping FailureClosure) -> Void {
    
    
    if hudSuperView != nil {
        MCHUD_default(message: "", view: hudSuperView, delay: 0)
    }
    
    let manager = AFHTTPSessionManager.init()
    manager.responseSerializer = AFJSONResponseSerializer.init()
    manager.responseSerializer.acceptableContentTypes =  NSSet.init(array: ["text/html","application/json"]) as? Set<String>
    
    manager.requestSerializer = AFJSONRequestSerializer.init()
    manager.requestSerializer.timeoutInterval = 10
    
    // 获取token
    let token = MCUserinfo_getToken()
    manager.requestSerializer.setValue(token, forHTTPHeaderField: "userToken")
    
    
    let paraDict = para as NSDictionary
    let allkeys = paraDict.allKeys
    

    
    
    
    let dictM = NSMutableDictionary.init(dictionary: para)
    
    var isContains_storeId = false

    for str in allkeys {
        let tempStr = str as? String ?? ""
        
        if tempStr == "storeId" {
            isContains_storeId = true
        }
    }
    
    if !isContains_storeId {
        dictM.setValue(MCUserinfo_getStoreId(), forKey: "storeId")
    }

    dictM.setValue(MCUserinfo_getUserId(), forKey: "userId")

    
    manager.post(url, parameters: dictM, progress: { (progress) in }, success: { (task, responseObject) in
        
        if hudSuperView != nil {
            MCHUD_hidden(view: hudSuperView)
        }
        
        
        let data : [String : Any] = responseObject as? [String:Any] ?? [:]
        
        let code:Int = data["code"] as? Int ?? 0
        
        
        switch code {
        case MCCode_success:
            success(responseObject as! [String : Any])
            break
        case MCCode_token:
            
            if vc != nil {
                MCAlterController_oneOptions(vc: vc!, message: "该账号已在别处登录,请重新登录", cancle: {
                    let login = MCLoginPageViewController()
                    MCPushToViewController(current: vc!, target: login, isHiddenBottomBarWhenBack: !isHiddenTabbar)
                })
            } else {
                dislike(responseObject as! [String : Any])
            }
            break
        default:
            dislike(responseObject as? [String : Any] ?? [:])
            
            let str = "接口: =\(url)\n" + "入参: =\(dictM)\n" + "结果: \(data)"
            print(str)
            let message = data["message"] as? String ?? ""
            
            
            if vc != nil {
                MCAlterController_oneOptions(vc: vc!, message: message, cancle: { })
            }
            
            break
        }
        
    }) { (task, error) in
        if hudSuperView != nil {
            MCHUD_hidden(view: hudSuperView)
        }
        let str =  "接口: =\(url)\n" + "入参: =\(dictM)\n" + "错误原因: \(error)"
        print(str)
        if vc != nil {
            MCAlterController_oneOptions(vc: vc!, message: "网络异常", cancle: { })
        }
    }
}
